import storage from 'good-storage'

const SEARCH_KEY = '__search__'
const SEARCH_MAX_LENGTH = 15

const PLAY_KEY = '__play__'
const PLAY_MAX_LENGTH = 200

const FAVORITE_KEY = '__favorite__'
const FAVORITE_MAX_LENGTH = 200

// 往searchHistory数组中插入数据调用的函数  compare是比较函数
function insertArray (arr, val, compare, maxLen) {
  // findIndex()是一个ES6的api, 可以接收一个函数
  const index = arr.findIndex(compare)
  if (index === 0) {
    return
  }
  if (index > 0) {
    arr.splice(index, 1)
  }
  // 没有该元素我们直接插入
  arr.unshift(val)
  // 再判断最大保存数量, 超出数量最后一个删除
  if (maxLen && arr.length > maxLen) {
    arr.pop() // 删除数组的最后一个数据
  }
}

// 这个方法是将query写入storage中, 然后再返回这个列表数据给vuex中
export function saveSearch (query) {
  // 如果没有存过就存放一个空数组先
  const searches = storage.get(SEARCH_KEY, [])
  // 1. 将数据插入
  insertArray(searches, query, (item) => {
    return item === query
  }, SEARCH_MAX_LENGTH)

  // 2. 将数据保存后返回出去
  storage.set(SEARCH_KEY, searches)
  return searches
}

export function loadSearch () {
  return storage.get(SEARCH_KEY, [])
}

function deleteFromArray (arr, compare) {
  const index = arr.findIndex(compare)
  if (index > -1) {
    arr.splice(index, 1)
  }
}

export function deleteSearch (query) {
  const searches = storage.get(SEARCH_KEY, [])
  deleteFromArray(searches, (item) => {
    return item === query
  })
  storage.set(SEARCH_KEY, searches)
  return searches
}

export function clearSearch () { // 清除storage所有对应key中的所有数据
  storage.remove(SEARCH_KEY)
  return []
}

export function savePlay (song) {
  // 从localStorage中获取PLAY_KEY对应的value, 如果不存在就给一个空数组
  const songs = storage.get(PLAY_KEY, [])
  insertArray(songs, song, (item) => {
    return item.id === song.id
  }, PLAY_MAX_LENGTH)
  storage.set(PLAY_KEY, songs)
  return songs
}

export function loadPlay () {
  return storage.get(PLAY_KEY, [])
}

export function saveFavorite(song) {
  const songs = storage.get(FAVORITE_KEY, [])
  insertArray(songs, song, (item) => {
    return song.id === item.id
  }, FAVORITE_MAX_LENGTH)
  storage.set(FAVORITE_KEY, songs)
  return songs
}

export function deleteFavorite(song) {
  const songs = storage.get(FAVORITE_KEY, [])
  deleteFromArray(songs, (item) => {
    return song.id === item.id
  })
  storage.set(FAVORITE_KEY, songs)
  return songs
}

export function loadFavorite() {
  return storage.get(FAVORITE_KEY, [])
}